package org.code.boot.controller.boot;

import java.util.List;

import org.code.boot.common.utils.DateUtils;
import org.springframework.security.access.prepost.PreAuthorize;
import java.util.Map;
import java.util.Collections;
import cn.hutool.core.collection.CollUtil;
import org.code.boot.common.utils.CollectionUtils;
import org.code.boot.common.utils.MapUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.code.boot.common.annotation.Log;
import org.code.boot.common.enums.BusinessType;
import org.code.boot.controller.BaseController;
import org.code.boot.vo.AjaxResult;
import org.code.boot.domain.boot.BizTrainOrder;
import org.code.boot.service.boot.IBizTrainOrderService;
import org.code.boot.vo.TableDataInfo;
import org.code.boot.domain.system.SysUser;
import org.code.boot.service.system.ISysUserService;
import org.code.boot.domain.boot.BizTrain;
import org.code.boot.service.boot.IBizTrainService;

/**
 * 火车票订单Controller
 * 
 * @author coder
 * @date 2025-08-28
 */
@RestController
@RequestMapping("/boot/trainorder")
public class BizTrainOrderController extends BaseController
{
    @Autowired
    private IBizTrainOrderService bizTrainOrderService;

    @Autowired
    private ISysUserService sysuserService;

    @Autowired
    private IBizTrainService biztrainService;
    @GetMapping("/seats/{trainId}")
    public AjaxResult getTrainSeats(@PathVariable Long trainId) {
        // 查询指定trainId的所有订单的seatNumber字段
        List<String> seatNumbers = bizTrainOrderService.getSeatNumbersByTrainId(trainId);
        return AjaxResult.success(seatNumbers);
    }
    /**
     * 查询火车票订单列表
     */
    @GetMapping("/list")
    public TableDataInfo list(BizTrainOrder bizTrainOrder)
    {
        startPage();
        List<BizTrainOrder> list = bizTrainOrderService.selectBizTrainOrderList(bizTrainOrder);
        list = buildDetailList(list);
        return getDataTable(list);
    }



    /**
     * 获取火车票订单下拉选项列表
     */
    @GetMapping("/options")
    public AjaxResult getOptions()
    {
        List<BizTrainOrder> list = bizTrainOrderService.selectBizTrainOrderList(new BizTrainOrder());
        return success(list);
    }

    /**
     * 获取当前用户的火车票订单列表
     */
    @GetMapping("/userOrders")
    public AjaxResult getUserTrainOrders()
    {
        BizTrainOrder queryParam = new BizTrainOrder();
        queryParam.setUserId(getUserId());
        List<BizTrainOrder> list = bizTrainOrderService.selectBizTrainOrderList(queryParam);
        list = buildDetailList(list);
        return success(list);
    }

    /**
     * 获取火车票订单详细信息
     */
    @GetMapping(value = "/{trainOrderId}")
    public AjaxResult getInfo(@PathVariable("trainOrderId") Long trainOrderId)
    {
        return success(bizTrainOrderService.selectBizTrainOrderByTrainOrderId(trainOrderId));
    }

    /**
     * 新增火车票订单
     */
    @Log(title = "火车票订单", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody BizTrainOrder bizTrainOrder)
    {
        bizTrainOrder.setCreateBy(getNickname());
        return toAjax(bizTrainOrderService.insertBizTrainOrder(bizTrainOrder));
    }

    /**
     * 修改火车票订单
     */
    @Log(title = "火车票订单", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody BizTrainOrder bizTrainOrder)
    {
        bizTrainOrder.setUpdateBy(getNickname());
        return toAjax(bizTrainOrderService.updateBizTrainOrder(bizTrainOrder));
    }

    /**
     * 删除火车票订单
     */
    @Log(title = "火车票订单", businessType = BusinessType.DELETE)
	@DeleteMapping("/{trainOrderIds}")
    public AjaxResult remove(@PathVariable Long[] trainOrderIds)
    {
        return toAjax(bizTrainOrderService.deleteBizTrainOrderByTrainOrderIds(trainOrderIds));
    }

    /**
     * 构建详细信息列表
     * 
     * @param list 列表数据
     * @return 构建后的列表数据
     */
    private List<BizTrainOrder> buildDetailList(List<BizTrainOrder> list) {
        if (CollUtil.isEmpty(list)) {
            return Collections.emptyList();
        }
        
        // 获取用户IDMap
        Map<Long, SysUser> userIdMap = sysuserService.getSysUserMap(
                CollectionUtils.convertSet(list, BizTrainOrder::getUserId));
        
        // 获取火车IDMap
        Map<Long, BizTrain> trainIdMap = biztrainService.getBizTrainMap(
                CollectionUtils.convertSet(list, BizTrainOrder::getTrainId));
        
        // 拼接结果
        list.forEach(item -> {
            // 拼接用户ID名称
            MapUtils.findAndThen(userIdMap, item.getUserId(), 
                userIdItem -> item.setUserIdName(userIdItem.getNickName()));
            // 拼接火车ID名称和出行日期
            MapUtils.findAndThen(trainIdMap, item.getTrainId(), 
                trainIdItem -> {
                    item.setTrainIdName(trainIdItem.getTrainName());
                    item.setTrainNumber(trainIdItem.getTrainNumber());
                    // 设置出行日期（使用火车的出发时间的日期部分）
                    if (trainIdItem.getDepartureTime() != null) {
                        item.setTravelDate(DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD, trainIdItem.getDepartureTime()));
                    }
                });
        });
        
        return list;
    }
}
